package my.page.impl;

import java.util.List;

import my.page.Engine;
import my.page.Page;
import my.page.PageParam;
/**
 * Page接口的实现类。
 * @author 夏冬琦
 *
 */
public class PageImpl implements Page {
	
	
	private int curr=Page.FIRST_PAGE;//当前页
	private int total;//总记录数
	private int pgTotal;//总页数
	private int rows=Page.ROWS_DEFAULT;//每页最大允许记录数
	
	private List<?> recList;//当前页数据
	
	
	public PageImpl(Engine engine,PageParam pageParam) throws PageException {
		
		/*
		 * 计算每页最大允许记录数
		 */
		try {
			this.rows = Integer.parseInt(pageParam.getRows());
		} catch (Exception e) {}
		
		if(this.rows<1) {
			throw new PageException("每页最大记录数不允许少于1.");
		}
		
		/*
		 * 计算总记录数
		 */
		try {			
			total=engine.getTotal();
		} catch (Exception e) {
			throw new PageException("获取总记录数失败！",e);
		}
		
		if(total<0) {
			throw new PageException("获取总不正确的记录数："+total+"！");
		}
		
		/*
		 * 计算总页数
		 */		
		if(total==0) {
			pgTotal=1;
		}else {
			if(total%rows==0) {
				pgTotal=total/rows;
			}else {
				pgTotal=total/rows+1;
			}
		}
		
		/*
		 * 计算当前页码
		 */		
		try {
			curr = Integer.parseInt(pageParam.getPage());
		} catch (Exception e) {}
		
		if(curr<getFirst())curr=getFirst();
		else if(curr>getLast())curr=getLast();
		
		
		/*
		 * 获取当前页数据
		 */
		try {
			this.recList=engine.getData((curr-1)*rows, curr*rows);
		} catch (Exception e) {
			throw new PageException("获取当前页数据失败！",e);
		}
				
	}
	

	@Override
	public int getFirst() {
		return Page.FIRST_PAGE;
	}

	@Override
	public int getPrevious() {
		return curr-1<getFirst()?getFirst():(curr-1);
	}

	@Override
	public int getNext() {
		return curr+1>getLast()?getLast():(curr+1);
	}

	@Override
	public int getLast() {
		return pgTotal;
	}

	@Override
	public int getCurr() {
		return curr;
	}

	@Override
	public int getRows() {
		return rows;
	}

	@Override
	public int getCurrRows() {
		return recList.size();
	}

	@Override
	public int getTotal() {
		return total;
	}

	@Override
	public int getPgTotal() {		
		return pgTotal;
	}

	@Override
	public List<?> getRecList() {		
		return recList;
	}

}
